<script setup>
import { ref, computed, watch } from 'vue'

let props = defineProps(['productList'])
const productList = props.productList

// 响应式变量
const selectedSpec = ref('')
const selectedColor = ref('')
const count = ref(1)
const selectedProduct = ref({})
const currentImg = ref(productList[0]?.url || '')
 
// 所有规格和颜色
const allSpecs = [...new Set(productList.map((item) => item.specifications[0]))]
const allColors = [
  ...new Set(productList.map((item) => item.specifications[1]))
]

// 规格点击事件 - 切换选中状态
const handleSpec = (spec) => {
  selectedSpec.value = selectedSpec.value === spec ? '' : spec
}

// 颜色点击事件 - 切换选中状态
const handleColor = (color) => {
  selectedColor.value = selectedColor.value === color ? '' : color
}

// 判断规格是否可用
const isSpecAvailable = (spec) => {
  if (!selectedColor.value) return true
  return productList.some(
    (item) =>
      item.specifications[0] === spec &&
      item.specifications[1] === selectedColor.value &&
      item.number > 0
  )
}

// 判断颜色是否可用
const isColorAvailable = (color) => {
  if (!selectedSpec.value) return true
  return productList.some(
    (item) =>
      item.specifications[0] === selectedSpec.value &&
      item.specifications[1] === color &&
      item.number > 0
  )
}

// 计算当前选中产品的最大可用数量
const maxCount = computed(() => {
  if (!selectedSpec.value || !selectedColor.value) return 0
  const product = productList.find(
    (item) =>
      item.specifications[0] === selectedSpec.value &&
      item.specifications[1] === selectedColor.value
  )
  return product?.number || 0
})

// 数量增减方法（增加库存检查）
const increment = () => {
  if (count.value < maxCount.value) {
    count.value++
  }
}

const decrement = () => {
  if (count.value > 1) {
    count.value--
  }
}

// 监听数量输入，确保不超过库存
const handleInput = (e) => {
  let value = parseInt(e.target.value) || 1
  if (value < 1) value = 1
  if (value > maxCount.value) value = maxCount.value
  count.value = value
}

// 监听选择变化，更新产品和图片
watch([selectedSpec, selectedColor], ([newSpec, newColor]) => {
  if (newSpec && newColor) {
    const product = productList.find(
      (item) =>
        item.specifications[0] === newSpec &&
        item.specifications[1] === newColor
    )
    if (product) {
      selectedProduct.value = product
      currentImg.value = product.url
    }
  }
})
</script>

<template>
  <div class="productList">
    <!-- 产品图片与价格 -->
    <div class="one">
      <img :src="currentImg" alt="产品图片" />
      <div class="desc">
        <div id="price">{{ '¥' + (selectedProduct.price || '--') }}</div>
        <div id="select">
          已选&nbsp;{{ selectedColor || '未选' }}&nbsp;{{
            selectedSpec || '未选'
          }}
        </div>
      </div>
    </div>

    <!-- 规格选择 -->
    <div class="spec">
      <p>规格</p>
      <p id="spec-item">
        <span
          v-for="spec in allSpecs"
          :key="spec"
          :class="{
            active: spec === selectedSpec,
            disabled: !isSpecAvailable(spec)
          }"
          @click="isSpecAvailable(spec) && handleSpec(spec)"
          >{{ spec }}</span
        >
      </p>
    </div>

    <!-- 颜色选择 -->
    <div class="color">
      <p>颜色</p>
      <p id="color-item">
        <span
          v-for="color in allColors"
          :key="color"
          :class="{
            active: color === selectedColor,
            disabled: !isColorAvailable(color)
          }"
          @click="isColorAvailable(color) && handleColor(color)"
          >{{ color }}</span
        >
      </p>
    </div>

    <!-- 购买数量 -->
    <div class="counter">
      <p>购买数量</p>
      <div>
        <button @click="decrement" :disabled="count <= 1">-</button>
        <input
          type="number"
          v-model="count"
          :max="maxCount"
          min="1"
          @change="handleInput"
        />
        <button @click="increment" :disabled="count >= maxCount">+</button>
      </div>
      <div v-if="maxCount > 0" class="stock-tip">库存: {{ maxCount }}件</div>
      <div v-else class="stock-tip out-of-stock">缺货</div>
    </div>

    <!-- 操作按钮 -->
    <div class="btn">
      <button :disabled="!selectedSpec || !selectedColor">加入购物车</button>
      <button :disabled="!selectedSpec || !selectedColor">立即购买</button>
    </div>
  </div>
</template>

<style scoped>
.productList {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

/* 产品图片与价格区域 */
.one {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  gap: 20px;
}
.one img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border: 1px solid #eee;
}
.desc {
  display: flex;
  flex-direction: column;
  justify-content: end;
  gap: 10px;
}
#price {
  color: red;
  font-size: 25px;
  font-weight: bold;
}
#select {
  color: #666;
  font-size: 15px;
}

/* 规格与颜色区域 */
.spec,
.color {
  margin: 15px 0;
}
.spec p:first-child,
.color p:first-child {
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
}
#spec-item,
#color-item {
  display: flex;
  gap: 10px;
}
/* 规格选择器样式 */
#spec-item span {
  padding: 5px 10px;
  border: 1px solid #ddd;
  cursor: pointer;
  border-radius: 4px;
}
#spec-item span.active {
  border-color: #ff4400;
  color: #ff4400;
}
#spec-item span.disabled {
  color: #ccc;
  cursor: not-allowed;
}

/* 颜色选择器样式 */
#color-item span {
  padding: 5px 10px;
  border: 1px solid #ddd;
  cursor: pointer;
  border-radius: 4px;
}
#color-item span.active {
  border-color: #ff4400;
  color: #ff4400;
}
#color-item span.disabled {
  color: #ccc;
  cursor: not-allowed;
}

/* 计数器样式 */
.counter {
  display: flex;
  align-items: center;
  margin: 20px 0;
  gap: 10px;
}
.counter p {
  color: #333;
  font-weight: bold;
}
.counter div {
  display: flex;
  align-items: center;
}
.counter button {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: #fff;
  cursor: pointer;
}
.counter input {
  width: 50px;
  height: 30px;
  text-align: center;
  border: 1px solid #ddd;
  border-left: none;
  border-right: none;
}
.counter button:disabled {
  cursor: not-allowed;
  color: #ccc;
}

/* 按钮样式 */
.btn {
  width: 100%;
  display: flex;
  gap: 10px;
  margin-top: 30px;
}
.btn button {
  flex: 1;
  height: 40px;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
}
.btn button:first-child {
  background: #ff4400;
}
.btn button:last-child {
  background: #ff6700;
}
.btn button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
/* 原有样式保持不变 */
.disabled {
  color: #ccc !important;
  cursor: not-allowed !important;
  pointer-events: none;
}

.stock-tip {
  margin-left: 10px;
  font-size: 12px;
  color: #666;
}

.out-of-stock {
  color: #ff4400;
}

/* 修改输入框样式，防止出现上下箭头 */
input[type='number'] {
  -moz-appearance: textfield;
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
